package com.example.androidtset;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class LoginActivity extends AppCompatActivity {
    private static final String SERVE_ADDRESS = "http://10.200.11.155:9000/userLogin";

    private EditText mUsername;
    private EditText mPassword;
    private Button loginBtn;
//    Handler handler = new Handler() {
//        @Override
//        public void handleMessage(@NonNull Message msg) {
//            if (msg.what == 1000) {
////                JSONObject
////                Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG).show();
//            }
//        }
//    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        init();

        Image();

        login();
    }

    private void init() {
        mUsername = findViewById(R.id.et_username);
        mPassword = findViewById(R.id.et_password);
        loginBtn = findViewById(R.id.btn_login);
    }

    private void login() {
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String username = mUsername.getText().toString();
                final String password = mPassword.getText().toString();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                        sendRequestByHttpUrlConnection(SERVE_ADDRESS);
                        String data = "{\"name\":\"" + username + "\",\"password\":\"" + password + "\"}";
                        sendPostRequestByHttpUrlConnection(SERVE_ADDRESS, data);
                    }
                }).start();
            }
        });
    }

    private void sendRequestByHttpUrlConnection(String requesturl) {
        HttpURLConnection connection = null;
        BufferedReader bufferedReader = null;
        try {
            URL url = new URL(requesturl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");


            connection.connect();
            if (connection.getResponseCode() == 200) {
                InputStream inputStream = connection.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                bufferedReader = new BufferedReader(inputStreamReader);
                String line = null;
                StringBuffer stringBuffer = new StringBuffer();
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }
                String request = stringBuffer.toString();

                Log.e("内容", request);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void sendPostRequestByHttpUrlConnection(String requesturl, String data) {
        HttpURLConnection connection = null;
        BufferedReader bufferedReader = null;
        try {
            URL url = new URL(requesturl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            connection.setRequestProperty("Content-Type", "application/json");

            connection.setDoOutput(true);
            connection.connect();
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(data.getBytes());

            if (connection.getResponseCode() == 200) {
                InputStream inputStream = connection.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                bufferedReader = new BufferedReader(inputStreamReader);
                String line = null;
                StringBuffer stringBuffer = new StringBuffer();
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }
                String request = stringBuffer.toString();

                JSONObject jsonObject = new JSONObject(request);
                final int error = jsonObject.optInt("error");
                final String msg = jsonObject.optString("msg");
//                if (Integer.parseInt(error) == 0) { }

//                Message message=new Message();
//                message.what=1000;
//                message.obj=jsonObject;
//                handler.sendMessage(message);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_LONG).show();
                        if (error == 0) {
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                        }
                    }
                });

                Log.e("内容", request);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {

            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void Image() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tx);
        RoundedBitmapDrawable circleDrawable = RoundedBitmapDrawableFactory.create(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.tx));
        circleDrawable.getPaint().setAntiAlias(true);
        circleDrawable.setCornerRadius(Math.max(bitmap.getWidth(), bitmap.getHeight()));
        ImageView imageView = findViewById(R.id.iv_image);
        imageView.setImageDrawable(circleDrawable);

        ViewGroup.LayoutParams params = imageView.getLayoutParams();
        params.height = 275;
        params.width = 275;
        imageView.setLayoutParams(params);
    }
}